<template>
  <div class="template-root-div">
    <div class="left-table">
      <div class="main">
        <mine-title>设备型号</mine-title>
        <div class="content">
          <div class="block-header">
            <div class="block-header-left">
              <mine-button type="primary" @click="addDict()"
                ><i class="iconfont icon-add-line"></i>新建设备型号
              </mine-button>
              <mine-button
                @click="deleteDict"
                secondary
                :disabled="!dictMultipleSelection.length"
                ><i class="iconfont icon-delete-line"></i>删除
              </mine-button>
              <mine-button
                type="primary"
                secondary
                @click="loadDictData(true, true)"
                ><i class="iconfont icon-reset-line"></i>刷新
              </mine-button>
            </div>
            <div class="block-header-right"></div>
          </div>
          <el-table
            class="table"
            :data="dictTableData"
            style="width: 100%"
            v-loading="dictLoading"
            @selection-change="handleDictSelectionChange"
            @row-click="dictRowClick"
            ref="multipleTable"
          >
            <el-table-column type="selection" width="45"></el-table-column>
            <el-table-column label="序号" show-overflow-tooltip width="60">
              <template slot-scope="scope">
                <!--                                <span>{{ scope.$index + (dictCurrentPage - 1) * dictPageSize + 1 }} </span>-->
                <span
                  >{{ scope.$index + (dictCurrentPage - 1) * dictPageSize + 1 }}
                </span>
              </template>
            </el-table-column>

            <el-table-column label="名称" prop="name" show-overflow-tooltip>
              <template slot="header">
                <span>名称</span>
                <mine-table-search
                  @searchSubmit="searchDictSubmit"
                  name="name"
                ></mine-table-search>
              </template>
            </el-table-column>
            <el-table-column
              label="设备编号"
              prop="typeCode"
              show-overflow-tooltip
            >
              <template slot="header">
                <span>设备编号</span>
                <mine-table-search
                  @searchSubmit="searchDictSubmit"
                  name="typeCode"
                ></mine-table-search>
              </template>
            </el-table-column>
            <el-table-column label="MTBF" prop="mtbf" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <mine-button type="text" @click="checkDict(scope.row)"
                  >详情</mine-button
                >
              </template>
            </el-table-column>
          </el-table>
          <mine-pagination
            @numberChange="dictNumberChange"
            :total="dictTotal"
            :page-size="dictPageSize"
            :current-page="dictCurrentPage"
          >
          </mine-pagination>
        </div>
      </div>
    </div>
    <div class="right-table">
      <div class="main">
        <mine-title>设备参数</mine-title>
        <div class="content">
          <div class="block-header">
            <div class="block-header-left">
              <mine-button
                type="primary"
                @click="addOption()"
                :disabled="!paramId"
                ><i class="iconfont icon-add-line"></i>新建参数
              </mine-button>
              <mine-button
                @click="deleteOption"
                secondary
                :disabled="!optionMultipleSelection.length"
                ><i class="iconfont icon-delete-line"></i>删除
              </mine-button>
              <mine-button
                type="primary"
                secondary
                @click="loadOptionData(true, true)"
              >
                <i class="iconfont icon-reset-line"></i>刷新
              </mine-button>
            </div>
            <div class="block-header-right"></div>
          </div>
          <el-table
            class="table"
            :data="optionTableData"
            style="width: 100%"
            v-loading="optionLoading"
            @selection-change="handleOptionSelectionChange"
            @row-click="dictOptionClick"
            ref="multipleTable"
          >
            <el-table-column type="selection" width="45"></el-table-column>
            <el-table-column label="序号" show-overflow-tooltip width="60">
              <template slot-scope="scope">
                <span
                  >{{
                    scope.$index + (optionCurrentPage - 1) * optionPageSize + 1
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="参数名称"
              prop="paramName"
              show-overflow-tooltip
            >
              <template slot="header">
                <span>参数名称</span>
                <!-- <mine-table-search
                  @searchSubmit="searchOptionSubmit"
                  name="paramName"
                ></mine-table-search> -->
              </template>
            </el-table-column>
            <el-table-column
              label="参数类型"
              prop="paramType"
              show-overflow-tooltip
              :formatter="paramTypeFormatter"
            >
              <template slot="header">
                <span>参数类型</span>
                <!-- <mine-table-search
                  @searchSubmit="searchOptionSubmit"
                  name="paramType"
                ></mine-table-search> -->
              </template>
            </el-table-column>
            <el-table-column
              label="维修类别"
              prop="repairType"
              show-overflow-tooltip
              :formatter="repairTypeFormatter"
            >
            </el-table-column>
            <el-table-column
              label="维修方式"
              prop="repairMethod"
              show-overflow-tooltip
              :formatter="repairMethodFormatter"
            >
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <mine-button type="text" @click="checkOption(scope.row)"
                  >详情</mine-button
                >
              </template>
            </el-table-column>
          </el-table>
          <mine-pagination
            @numberChange="optionNumberChange"
            :total="optionTotal"
            :page-size="optionPageSize"
            :current-page="optionCurrentPage"
          >
          </mine-pagination>
        </div>
      </div>
    </div>
    <!-- 弹框区 -->
    <mine-dialog
      :top="'4vh'"
      :dialogFormVisible="deviceTypeAddFlag || deviceTypeEditFlag"
      :width="'800px'"
      :showClose="true"
      :title="deviceTypeTitle"
    >
      <AddInstance
        v-if="deviceTypeAddFlag"
        slot="option"
        @changeFlag="closeDialog"
      ></AddInstance>
      <EditInstance
        v-if="deviceTypeEditFlag"
        slot="option"
        @changeFlag="closeDialog"
        :rowData="deviceTypeRowData"
      ></EditInstance>
    </mine-dialog>
  </div>
</template>

<script>
import qs from "qs";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";
import AddInstance from "./components/addInstance.vue";
import EditInstance from "./components/instanceDetail.vue";

export default {
  components: {
    AddInstance,
    EditInstance,
  },
  data() {
    return {
      tableHeight: window.innerHeight - 330,
      // left-table参数
      dictListQuery: {},
      dictTableData: [],
      dictTotal: 0,
      dictPageSize: 10,
      dictCurrentPage: 1,
      dictMultipleSelection: [],
      dictLoading: false,

      // right-table参数
      optionListQuery: {},
      optionTableData: [],
      optionTotal: 0,
      optionPageSize: 10,
      optionCurrentPage: 1,
      optionMultipleSelection: [],
      optionLoading: false,
      paramId: 0,
      deviceTypeAddFlag: false, // 设备型号左列表
      deviceTypeRowData: {}, // 左列表选中数据
      deviceTypeTitle: "新建设备型号", //
      deviceTypeEditFlag: false, // 设备弹框
    };
  },
  methods: {
    closeDialog() {
      this.deviceTypeAddFlag = false;
      this.deviceTypeEditFlag = false;
      this.loadData(true);
    },
    searchDictSubmit(value) {
      if (value.key === "name") {
        this.dictListQuery.name = value.value;
      }
      if (value.key === "typeCode") {
        this.dictListQuery.typeCode = value.value;
      }
      if (value.key === "isSystem") {
        switch (value.value) {
          case "否":
            this.dictListQuery.isSystem = 1;
            break;
          case "是":
            this.dictListQuery.isSystem = 0;
            break;
        }
      }
      this.loadDictData(true);
    },
    searchOptionSubmit(value) {
      if (value.key === "optCode") {
        this.optionListQuery.optCode = value.value;
      }
      if (value.key === "optName") {
        this.optionListQuery.optName = value.value;
      }
      this.loadOptionData(true);
    },
    async loadData(flag) {
      await this.loadDictData(flag);
      // await this.loadOptionData(flag)
    },
    addDict() {
      // this.$store.commit("SET_DICT_NUMBER", Number(this.dictTotal));
      // this.$router.push({
      //   path: "/equipAdmin/addInstance",
      // });
      this.deviceTypeAddFlag = true;
    },
    async deleteDict() {
      this.$mineConfirm("确认要删除", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const ids = this.dictMultipleSelection.map((item) => item.id);
          this.dictLoading = true;
          try {
            let res = {};
            let _self = this;
            if (_self.$qwebUtil.isQtClient) {
              const uuid = _self.$qwebUtil.generateRandomUUID();
              let sendObject;
              /* eslint-disable-next-line */
              const channel = new QWebChannel(
                window.qt.webChannelTransport,
                async function (channel) {
                  sendObject = channel.objects.sendObject;
                  // receivedJSON 修改此处发送请求参数
                  const receivedJSON = {
                    RequestUrl: `/equipCatalog/deleteByIds${_self.$qwebUtil.convertIdsToQueryString(
                      ids
                    )}`,
                    RequestMethod: "post",
                    ContentType: "application/json;charset=UTF-8",
                    RequestBody: {},
                    isStringParam: false,
                    requestId: uuid,
                  };
                  await send();
                  await _self.$qwebUtil.receive(sendObject, receivedJSON);
                  // console.error('received','/feCanvas/pageList')
                }
              );
              /* eslint-disable-next-line */
              async function send() {
                sendObject.sendMessage.connect(function (data) {
                  if (!data) {
                    console.error("No data received.");
                  }
                  res = JSON.parse(data);
                  const result = res.response || {};
                  // update the followings
                  if (result.success && res.webInfo.requestId == uuid) {
                    _self.$message.success("删除成功");
                    _self.loadData(true);
                  } else {
                    _self.$message.error(result.msg || "删除失败");
                  }
                });
              }
            } else if (this.$webview2.isWPF) {
              const uuid = this.$webview2.generateRandomUUID();
              await this.$webview2.sendWebView2(
                `/equipCatalog/deleteByIds${this.$webview2.convertIdsToQueryString(
                  ids
                )}`,
                "post",
                "application/json;charset=UTF-8",
                {},
                false,
                uuid
              );
              await window.chrome.webview.addEventListener(
                "message",
                (e) => {
                  res = e.data;
                  const result = res.response || {};
                  if (result.success && res.webInfo.requestId == uuid) {
                    this.$message.success("删除成功");
                    this.loadData(true);
                  } else {
                    this.$message.error(result.msg || "删除失败");
                  }
                },
                {
                  once: true,
                }
              );
            } else {
              res = await this.$store.dispatch("equipCatalogListBatchDelete", {
                ids: ids,
              });
              const result = res.data || {};
              if (result.success) {
                this.$message.success("删除成功");
                await this.loadData(true);
              } else {
                this.$message.error(result.msg || "删除失败");
              }
            }
          } catch (e) {
            console.error(e);
          }
          this.dictLoading = false;
        })
        .catch(() => {});
    },
    async loadDictData(flag, refresh = false) {
      if (flag) {
        this.dictCurrentPage = 1;
      }
      if (refresh) {
        this.dictListQuery = {};
      }
      const params = {
        ...this.dictListQuery,
        page: this.dictCurrentPage,
        pageSize: this.dictPageSize,
      };
      this.dictLoading = true;

      let res = {};
      let _self = this;
      try {
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: "/equipCatalog/pageList",
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: qs.stringify(params, { indices: false }),
                isStringParam: true,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                const data = result.data;
                _self.dictTableData =
                  data.list && data.list.length ? data.list : [];
                _self.dictTotal = data.rowCount || 0;
              } else {
                _self.dictTableData = [];
                _self.total = 0;
              }
            });
          }
        } else if (this.$webview2.isWPF) {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            "/equipCatalog/pageList",
            "get",
            "application/json;charset=UTF-8",
            qs.stringify(params, { indices: false }),
            true,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              res = e.data;
              const result = res.response || {};
              console.log(result);
              // TODO： 定制后台数据处理
              if (result.success && res.webInfo.requestId == uuid) {
                const data = result.data;
                this.dictTableData =
                  data.list && data.list.length ? data.list : [];
                this.dictTotal = data.rowCount || 0;
              } else {
                this.dictTableData = [];
                this.total = 0;
              }
            },
            {
              once: true,
            }
          );
        } else {
          res = await this.$store.dispatch(
            "equipCatalogPageList",
            qs.stringify(params, { indices: false })
          );
          const result = res.data || {};
          // TODO： 定制后台数据处理
          if (result.success) {
            const data = result.data;
            this.dictTableData = data.list && data.list.length ? data.list : [];
            this.dictTotal = data.rowCount || 0;
          } else {
            this.dictTableData = [];
            this.total = 0;
          }
        }
      } catch (e) {
        console.error(e);
      }
      this.dictLoading = false;
    },
    addOption() {
      // console.log(this.paramId);
      if (this.paramId === 0) {
        this.$message.error("请先选择对应的设备型号");
      } else {
        // this.$store.commit(
        //     "SET_OPTION_NUMBER",
        //     Number(this.optionTotal)
        // );
        this.$router.push({
          path: "/equipAdmin/addParam",
          // query: String(this.paramId)
        });
      }
    },
    async deleteOption() {
      this.$mineConfirm("确认要删除", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const ids = this.optionMultipleSelection.map((item) => item.id);
          this.optionLoading = true;
          try {
            let res = {};
            let _self = this;
            if (_self.$qwebUtil.isQtClient) {
              const uuid = _self.$qwebUtil.generateRandomUUID();
              let sendObject;
              /* eslint-disable-next-line */
              const channel = new QWebChannel(
                window.qt.webChannelTransport,
                async function (channel) {
                  sendObject = channel.objects.sendObject;
                  // receivedJSON 修改此处发送请求参数
                  const receivedJSON = {
                    RequestUrl: `/equipCheck/deleteByIds${_self.$qwebUtil.convertIdsToQueryString(
                      ids
                    )}`,
                    RequestMethod: "post",
                    ContentType: "application/json;charset=UTF-8",
                    RequestBody: {},
                    isStringParam: false,
                    requestId: uuid,
                  };
                  await send();
                  await _self.$qwebUtil.receive(sendObject, receivedJSON);
                  // console.error('received','/feCanvas/pageList')
                }
              );
              /* eslint-disable-next-line */
              async function send() {
                sendObject.sendMessage.connect(function (data) {
                  if (!data) {
                    console.error("No data received.");
                  }
                  res = JSON.parse(data);
                  const result = res.response || {};
                  // update the followings
                  if (result.success && res.webInfo.requestId == uuid) {
                    _self.$message.success("删除成功");
                    // await _self.loadData(true);
                    _self.loadOptionData(
                      true,
                      false,
                      _self.$store.state.dictAdmin.currentDirId
                    );
                  } else {
                    _self.$message.error(result.msg || "删除失败");
                  }
                });
              }
            } else if (this.$webview2.isWPF) {
              const uuid = this.$webview2.generateRandomUUID();
              await this.$webview2.sendWebView2(
                `/equipCheck/deleteByIds${this.$webview2.convertIdsToQueryString(
                  ids
                )}`,
                "post",
                "application/json;charset=UTF-8",
                {},
                false,
                uuid
              );
              await window.chrome.webview.addEventListener(
                "message",
                (e) => {
                  res = e.data;
                  const result = res.response || {};
                  if (result.success && res.webInfo.requestId == uuid) {
                    this.$message.success("删除成功");
                    // await this.loadData(true);
                    this.loadOptionData(
                      true,
                      false,
                      this.$store.state.dictAdmin.currentDirId
                    );
                  } else {
                    this.$message.error(result.msg || "删除失败");
                  }
                },
                {
                  once: true,
                }
              );
            } else {
              res = await this.$store.dispatch("equipCheckListBatchDelete", {
                ids: ids,
              });
              const result = res.data || {};
              if (result.success) {
                this.$message.success("删除成功");
                // await this.loadData(true);
                await this.loadOptionData(
                  true,
                  false,
                  this.$store.state.dictAdmin.currentDirId
                );
              } else {
                this.$message.error(result.msg || "删除失败");
              }
            }
          } catch (e) {
            console.error(e);
          }
          this.optionLoading = false;
        })
        .catch(() => {});
    },
    async loadOptionData(flag, refresh = false, paramId = this.paramId) {
      if (flag) {
        this.optionCurrentPage = 1;
      }
      if (refresh) {
        this.optionListQuery = {};
      }
      const params = {
        ...this.optionListQuery,
        catalogId: paramId,
        page: this.optionCurrentPage,
        pageSize: this.optionPageSize,
      };
      this.optionLoading = true;

      try {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: "/equipCheck/pageList",
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: qs.stringify(params, { indices: false }),
                isStringParam: true,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                const data = result.data;
                _self.optionTableData =
                  data.list && data.list.length ? data.list : [];
                _self.optionTotal = data.rowCount || 0;
              } else {
                _self.optionTableData = [];
                _self.optionTotal = 0;
              }
            });
          }
        } else if (this.$webview2.isWPF) {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            "/equipCheck/pageList",
            "get",
            "application/json;charset=UTF-8",
            qs.stringify(params, { indices: false }),
            true,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              res = e.data;
              const result = res.response || {};
              if (result.success && res.webInfo.requestId == uuid) {
                const data = result.data;
                this.optionTableData =
                  data.list && data.list.length ? data.list : [];
                this.optionTotal = data.rowCount || 0;
              } else {
                this.optionTableData = [];
                this.optionTotal = 0;
              }
            },
            {
              once: true,
            }
          );
        } else {
          res = await this.$store.dispatch(
            "equipCheckPageList",
            qs.stringify(params, { indices: false })
          );
          const result = res.data || {};
          // TODO： 定制后台数据处理
          if (result.success) {
            const data = result.data;
            this.optionTableData =
              data.list && data.list.length ? data.list : [];
            this.optionTotal = data.rowCount || 0;
          } else {
            this.optionTableData = [];
            this.optionTotal = 0;
          }
        }
      } catch (e) {
        console.error(e);
      }
      this.optionLoading = false;
    },
    // 查看详情
    checkDict(val) {
      this.deviceTypeRowData = val;
      this.deviceTypeEditFlag = true;
    },
    checkOption(val) {
      this.$router.push({
        path: "/equipAdmin/paramDetail",
        query: {
          id: val.id,
        },
      });
    },
    // 多选
    handleDictSelectionChange(selection) {
      this.dictMultipleSelection = selection;
    },
    handleOptionSelectionChange(selection) {
      this.optionMultipleSelection = selection;
    },
    dictNumberChange(val) {
      switch (val.flag) {
        case "pageSize":
          this.dictPageSize = val.pageSize;
          this.loadDictData(true);
          break;
        case "currentPage":
          this.dictCurrentPage = val.currentPage;
          this.loadDictData(false);
          break;
        default:
          break;
      }
    },
    optionNumberChange(val) {
      switch (val.flag) {
        case "pageSize":
          this.optionPageSize = val.pageSize;
          this.loadOptionData(true);
          break;
        case "currentPage":
          this.optionCurrentPage = val.currentPage;
          this.loadOptionData(false);
          break;
        default:
          break;
      }
    },
    // table格式化部分
    paramTypeFormatter(row) {
      if (row.paramType === 1) {
        return "数值";
      } else if (row.paramType === 2) {
        return "字符串";
      } else {
        return "";
      }
    },
    repairTypeFormatter(row) {
      if (row.repairType === 1) {
        return "事后维修";
      } else if (row.repairType === 2) {
        return "定期维修";
      } else if (row.repairType === 3) {
        return "视情维修";
      } else {
        return "";
      }
    },
    repairMethodFormatter(row) {
      if (row.repairMethod === 1) {
        return "维修保养";
      } else if (row.repairMethod === 2) {
        return "更换备件";
      } else if (row.repairMethod === 3) {
        return "原件修复";
      } else {
        return "";
      }
    },
    // table事件
    dictRowClick(row) {
      // console.log(row)
      this.loadOptionData(true, false, row.id);
      this.$store.commit("SET_CURRENT_PARAM_ID", row.id);
      this.paramId = row.id;
    },
    dictOptionClick(row) {},
  },
  mounted() {
    this.loadData();
  },
};
</script>

<style scoped lang="less">
.template-root-div {
  display: flex;
}

.left-table {
  flex: 1;
  height: 100%;
}

.right-table {
  flex: 1;
  height: 100%;
  padding-left: 1%;
}
</style>
